<?php
/**
* phpCan - http://idc.anavallasuiza.com/
*
* phpCan is released under the GNU Affero GPL version 3
*
* More information at license.txt
*/

namespace data\formats;

defined('ANS') or die();

class Title extends Formats implements iFormats {
	var $format = 'title';

	public function check ($value) {
		$this->error = array();

		return $this->validate($value);
	}

	public function valueDB (\data\Data $Data, $value, $language = '', $id = 0) {
		$value['title'] = strip_tags($value['title']);

		$url_text = alphaNumeric($value['title'], true);

		if (empty($url_text)) {
			$url_text = uniqid();
		}

		if ($this->settings['url']['unique']) {
			$field = $this->getField('url', $language);
			$url_text_base = $url_text;
			$num = 0;

			$exists_query = array(
				'table' => $this->table,
				'conditions' => array(
					$field => $url_text
				),
				'comment' => __('Checking for duplications in %s', $field)
			);

			if ($id) {
				$exists_query['conditions']['id !='] = $id;
			}

			while ($Data->selectCount($exists_query)) {
				$exists_query['conditions'][$field] = $url_text = $url_text_base.'-'.($num++);
			}
		}

		$return = array(
			'title' => $value['title'],
			'url' => $url_text
		);

		return $return;
	}

	public function settings ($settings) {
		$this->settings = $this->setSettings($settings, array(
			'title' => array(
				'db_type' => 'varchar',

				'length_max' => 255,
				'length_min' => '',
			),
			'url' => array(
				'db_type' => 'varchar',

				'unique' => $this->name,
				'length_max' => 255,
				'length_min' => '',
			)
		));

		return $this->settings;
	}
}
?>
